/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.mybatis.wizard;

import java.io.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
import org.w3c.dom.*;

import java.awt.Component;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import javax.swing.JComponent;
import javax.swing.event.ChangeListener;

import org.netbeans.api.templates.TemplateRegistration;
import org.openide.util.NbBundle.Messages;
import org.netbeans.api.java.project.JavaProjectConstants;
import org.netbeans.api.project.Project;
import org.netbeans.api.project.ProjectUtils;
import org.netbeans.api.project.SourceGroup;
import org.netbeans.api.project.Sources;
import org.netbeans.spi.java.project.support.ui.templates.JavaTemplates;
import org.netbeans.spi.project.ui.templates.support.Templates;
import org.openide.WizardDescriptor;
import org.openide.filesystems.FileObject;
import org.openide.loaders.DataFolder;
import org.openide.loaders.DataObject;
import org.openide.util.Exceptions;
// TODO define position attribute
@TemplateRegistration(folder = "asmFiles", displayName = "#MyBatisMapperWizardIterator_displayName", iconBase = "org/mybatis/wizard/VeicoloCar.png", description = "letter.html")
@Messages("MyBatisMapperWizardIterator_displayName=TemplateMapperMyBatis")
public final class MyBatisMapperWizardIterator implements WizardDescriptor.InstantiatingIterator<WizardDescriptor> {

    private int index;
    private WizardDescriptor wizard;
    private List<WizardDescriptor.Panel<WizardDescriptor>> panels;
    private WizardDescriptor.Panel packageChooserPanel;

    private List<WizardDescriptor.Panel<WizardDescriptor>> getPanels() {
        Project project = Templates.getProject(wizard);
        //Sources sources = (Sources) project.lookup(Sources.class);
        //Sources sources = (Sources) project.getLookup().lookup(Sources.class);
        Sources sources = (Sources) ProjectUtils.getSources(project);
        SourceGroup[] groups = sources.getSourceGroups(JavaProjectConstants.SOURCES_TYPE_JAVA);
        packageChooserPanel = JavaTemplates.createPackageChooser(project, groups, new MyBatisMapperWizardPanel1());


        if (panels == null) {
            panels = new ArrayList<WizardDescriptor.Panel<WizardDescriptor>>();
            panels.add(new MyBatisMapperWizardPanel2());

            panels.add(packageChooserPanel);
            String[] steps = createSteps();
            for (int i = 0; i < panels.size(); i++) {
                Component c = panels.get(i).getComponent();
                if (steps[i] == null) {
                    // Default step name to component name of panel. Mainly
                    // useful for getting the name of the target chooser to
                    // appear in the list of steps.
                    steps[i] = c.getName();
                }
                if (c instanceof JComponent) { // assume Swing components
                    JComponent jc = (JComponent) c;
                    jc.putClientProperty(WizardDescriptor.PROP_CONTENT_SELECTED_INDEX, i);
                    jc.putClientProperty(WizardDescriptor.PROP_CONTENT_DATA, steps);
                    jc.putClientProperty(WizardDescriptor.PROP_AUTO_WIZARD_STYLE, true);
                    jc.putClientProperty(WizardDescriptor.PROP_CONTENT_DISPLAYED, true);
                    jc.putClientProperty(WizardDescriptor.PROP_CONTENT_NUMBERED, true);
                }
            }
        }
        return panels;
    }

    @Override
    public Set<?> instantiate() throws IOException {
//        // TODO return set of FileObject (or DataObject) you have created
//        
//        //Prepare the arguments for passing to the FreeMarker template:
        String xmlString = (String) wizard.getProperty(MyBatisMapperVisualPanel2.XMLSTRING);
        String implementation = (String) wizard.getProperty(MyBatisMapperVisualPanel1.IMPLEMENTATION);
        Map args = new HashMap();
       // args.put("url", "extends " + extension);
        args.put("name", "implements " + implementation);
        args.put("types", "implements " + implementation);
        
//
//    //Get the template and convert it:
        FileObject template = Templates.getTemplate(wizard);
        DataObject dTemplate = DataObject.find(template);
//
//    //Get the package:
        FileObject dir = Templates.getTargetFolder(wizard);
        DataFolder df = DataFolder.findFolder(dir);
//
//    //Get the class:
        String targetName = Templates.getTargetName(wizard);
//
//    //Define the template from the above,
//    //passing the package, the file name, and the map of strings to the template:
        DataObject dobj = dTemplate.createFromTemplate(df, targetName + ".xml", args);

        scribir(dobj.getPrimaryFile().getPath(),xmlString);
//    //Obtain a FileObject:
        FileObject createdFile = dobj.getPrimaryFile();



        //createdFile=   FileUtil.createData(new File(""));
        return Collections.singleton(createdFile);
//        

        //return Collections.emptySet();
    }

    private void scribir(String filestr,String xmlString) {
        try {
            writeXml();
        } catch (Exception ex) {
            Exceptions.printStackTrace(ex);
        }
        
        FileOutputStream DiscoFileStream = null;//Percorso in uscita
        PrintStream Disco; //Oggetto che punta a
        File DiscoFile; //Il file

        DiscoFile = new File(filestr);
        try {
            DiscoFileStream = new FileOutputStream(DiscoFile);
        } catch (FileNotFoundException ex) {
            Exceptions.printStackTrace(ex);
        }
        Disco = new PrintStream(DiscoFileStream);

        //System.out.println("Prima riga"); //Questa riga scrive a video
        Disco.println(xmlString); //Questa nel file dati.txt
    }

    private void writeXml() throws Exception {

        
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Enter number to add elements in your XML file: ");
        //String str = bf.readLine();
        int no = 2;
        //System.out.print("Enter root: ");
        String root ="Mapper"; //bf.readLine();
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = documentBuilder.newDocument();
        Element rootElement = document.createElement(root);
        document.appendChild(rootElement);
        for (int i = 1; i <= no; i++) {
            System.out.print("Enter the element: ");
            String element = bf.readLine();
            System.out.print("Enter the data: ");
            String data = bf.readLine();
            Element em = document.createElement(element);
            
            em.appendChild(document.createTextNode(data));
            rootElement.appendChild(em);
        }
        
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(document);
        StreamResult result = new StreamResult(System.out);
        transformer.transform(source, result);

    }

//    private String getXmlMyBatis(){
//    try { 
//      //Elemento radice 
//      Element root = new Element("TODO_LIST"); 
//      //Documento 
//      Document document = new Document(root); 
//
//      //Creazione di tre elementi figli denominato ITEM 
//      //a ciascuno dei quali vengono settati tre attributi 
//      //e viene aggiunto un elemento figlio contenente 
//      //la descrizione della cosa da fare 
//      Element item1 = new Element("ITEM"); 
//      item1.setAttribute("importanza", "3"); 
//      item1.setAttribute("perc_completamento", "75"); 
//      item1.setAttribute("completata", "no"); 
//      Element descr1 = new Element("DESCR"); 
//      descr1.setText("Fare la spesa"); 
//      item1.addContent(descr1); 
//      root.addContent(item1); 
//
//      Element item2 = new Element("ITEM"); 
//      item2.setAttribute("importanza", "7"); 
//      item2.setAttribute("perc_completamento", "100"); 
//      item2.setAttribute("completata", "si"); 
//      Element descr2 = new Element("DESCR"); 
//      descr2.setText("Stendere i panni"); 
//      item2.addContent(descr2); 
//      root.addContent(item2); 
//
//      Element item3 = new Element("ITEM"); 
//      item3.setAttribute("importanza", "4"); 
//      item3.setAttribute("perc_completamento", "0"); 
//      item3.setAttribute("completata", "no"); 
//      Element descr3 = new Element("DESCR"); 
//      descr3.setText("Cucinare"); 
//      item3.addContent(descr3); 
//      root.addContent(item3); 
//
//      //Creazione dell'oggetto XMLOutputter 
//      XMLOutputter outputter = new XMLOutputter(); 
//      //Imposto il formato dell'outputter come "bel formato" 
//      outputter.setFormat(Format.getPrettyFormat()); 
//      //Produco l'output sul file xml.foo 
//      outputter.output(document, new FileOutputStream("foo.xml")); 
//      System.out.println("File creato:"); 
//      //Stampo l'output anche sullo standard output 
//      outputter.output(document, System.out); 
//    }  
//    catch (IOException e) { 
//      System.err.println("Errore durante il parsing del documento");
//      e.printStackTrace(); 
//    } 
//
//    
//    return "";
//    }
    @Override
    public void initialize(WizardDescriptor wizard) {
        this.wizard = wizard;
    }

    @Override
    public void uninitialize(WizardDescriptor wizard) {
        panels = null;
    }

    @Override
    public WizardDescriptor.Panel<WizardDescriptor> current() {
        return getPanels().get(index);
    }

    @Override
    public String name() {
        return index + 1 + ". from " + getPanels().size();
    }

    @Override
    public boolean hasNext() {
        return index < getPanels().size() - 1;
    }

    @Override
    public boolean hasPrevious() {
        return index > 0;
    }

    @Override
    public void nextPanel() {
        if (!hasNext()) {
            throw new NoSuchElementException();
        }
        index++;
    }

    @Override
    public void previousPanel() {
        if (!hasPrevious()) {
            throw new NoSuchElementException();
        }
        index--;
    }

    // If nothing unusual changes in the middle of the wizard, simply:
    @Override
    public void addChangeListener(ChangeListener l) {
    }

    @Override
    public void removeChangeListener(ChangeListener l) {
    }
    // If something changes dynamically (besides moving between panels), e.g.
    // the number of panels changes in response to user input, then use
    // ChangeSupport to implement add/removeChangeListener and call fireChange
    // when needed

    // You could safely ignore this method. Is is here to keep steps which were
    // there before this wizard was instantiated. It should be better handled
    // by NetBeans Wizard API itself rather than needed to be implemented by a
    // client code.
    private String[] createSteps() {
        String[] beforeSteps = (String[]) wizard.getProperty("WizardPanel_contentData");
        assert beforeSteps != null : "This wizard may only be used embedded in the template wizard";
        String[] res = new String[(beforeSteps.length - 1) + panels.size()];
        for (int i = 0; i < res.length; i++) {
            if (i < (beforeSteps.length - 1)) {
                res[i] = beforeSteps[i];
            } else {
                res[i] = panels.get(i - beforeSteps.length + 1).getComponent().getName();
            }
        }
        return res;
    }
}
